package com.example.day_day_up.servlet;

import com.example.day_day_up.config.AppConfig;
import com.example.day_day_up.entity.constants.Constants;
import com.example.day_day_up.entity.dto.WebUserDTO;
import com.example.day_day_up.service.UserService;
import com.example.day_day_up.utils.FileUpload;
import com.example.day_day_up.utils.JsonUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@WebServlet(urlPatterns = {"/file/*", "/file"})
public class FileServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext servletContext = getServletContext();
        userService = (UserService) servletContext.getAttribute("userService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestPath = req.getPathInfo();
        String filePath = AppConfig.FILE_UPLOAD_RESOURCE + requestPath;

        File file = new File(filePath);
        // 检查文件是否存在
        if (file.exists() && !file.isDirectory()) {
            // 设置响应的内容类型
            String contentType = getServletContext().getMimeType(file.getName());
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            resp.setContentType(contentType);

            // 将文件内容写入响应输出流
            FileInputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = resp.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();
        } else {
            JsonUtils.writeErrorResponse(resp, "文件解析失败 || 文件不存在");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");
        if (ServletFileUpload.isMultipartContent(req)) {
            try {
                // 获取表单信息
                List<FileItem> list = getFileItemsFromRequest(req);
                for (FileItem item : list) {
                    if (!item.isFormField()) {
                        String storeName = FileUpload.upload(item);
                        handleFileUploadResult(type, storeName, req);
                    }
                }
            } catch (FileUploadException e) {
                JsonUtils.writeErrorResponse(resp, "文件上传失败");
            }
        }
    }

    private List<FileItem> getFileItemsFromRequest(HttpServletRequest req) throws FileUploadException {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        return servletFileUpload.parseRequest(req);
    }

    private void handleFileUploadResult(String type, String storeName, HttpServletRequest req) {
        if (type.equals("avatar")) {
            String avatar = Constants.DEFAULT_URL + AppConfig.FILE_AVATAR + storeName;
            userService.updateAvatar(avatar, req);
        }
    }
}
